<?php

namespace app\web\service;

use app\common\logic\SmsLogic;
use app\common\model\commonModel;
use app\common\model\trCache;
use app\common\model\trDriver;
use app\common\model\trOrder;
use app\common\model\trSystemSet;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\Db;

/**
 * Class Auth
 * @package app\admin\service
 * 司机服务类
 */
class DriverService
{
    private $returnData;
    private $params;

    public function __construct($data, $params)
    {
        $this->returnData = $data;
        $this->params = $params;
    }

    // 司机首页信息
    public function driverIndex(){
        $model = new trDriver();
        $data = $model->getFields("nickname,prefix,mobile,avatar,balance,order_taking,status", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(empty($data)){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "司机不存在";
            return $this->returnData;
        }
        if($data["status"] == "3"){ //1正常；2休息；3注销
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "司机已被注销，请联系管理员";
            return $this->returnData;
        }
        $onlineStatus = trSystemSet::getValue("wxAppDriverOnlineStatus");
        $walletStatus = trSystemSet::getValue("wxAppWalletStatus");
        $data["setting"] = ["walletStatus" => isset($walletStatus["status"]) ? $walletStatus["status"] : '1', "onlineStatus" => isset($onlineStatus["status"]) ? $onlineStatus["status"] : '1'];
        $this->returnData["data"] = $data;
        return $this->returnData;
    }

    // 司机基本信息
    public function driverInfo(){
        $model = new trDriver();
        $data = $model->getFields("nickname,prefix,mobile,id_card,gender", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(empty($data)){
            return ErrorCode::code("customized", "该用户不是司机");
        }
        $this->returnData["data"] = $data;
        return $this->returnData;
    }

    // 司机基本信息
    public function updateDriverInfo(){
        $field = ["nickname" => "require", "prefix" => "require", "mobile" => "require", "id_card" => "require", "gender" => "require"];
        $data = [];
        foreach ($field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if(!isset($this->params[$ks])){
                return ErrorCode::code('params_not_exist', $ks);
            }
            $data[$k] = $this->params[$ks];
        }
        $model = new trDriver();
        $res = $model->doUpdate($data, ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(isset($res["code"])) {
            return $res;
        }
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "更新失败";
        }
        return $this->returnData;
    }

    // 更新司机状态
    public function updateDriverStatus(){ // status  状态：1正常；2休息；3注销
        if(empty($this->params['status'])){
            return ErrorCode::code("params_not_exist", "status");
        }
        if(!in_array($this->params["status"], [1,2])){
            return ErrorCode::code("params_error", "status（1正常；2休息）");
        }
        $model = new trDriver();
        $res = $model->doUpdate(["status" => $this->params["status"]], ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "更新失败";
        }
        return $this->returnData;
    }

    // 司机钱包列表
    public function driverWallet(){
        $model = new trDriver();
        $data = $model->getFields("id,balance", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]], true, false);
        if(empty($data)){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "司机不存在";
            return $this->returnData;
        }
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 20;
        $orderData = commonModel::getList(orderCommissionTable, "order_sn,money,pay_time", ["driver_id" => $data["id"]], $page, $pageSize);
        $this->returnData["data"] = ["balance" => $data["balance"]];
        if(!$orderData["data"]){
            $this->returnData['data']["orderData"] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            foreach ($orderData["data"] as $k => $v){
                $orderData["data"][$k]["payTime"] = date("Y-m-d H:i", $v["payTime"]);
            }
            $this->returnData['data']["orderData"] = ['list' => $orderData['data'], 'totalPage' => $orderData['last_page'], 'currentPage' => $orderData['current_page'], 'count' => $orderData['total']];
        }
        return $this->returnData;
    }

    // 司机提现
    public function toDriverWithdraw(){
        if(empty($this->params['money'])){
            return ErrorCode::code("params_not_exist", "money");
        }
        if($this->params['money'] <= 0){
            return ErrorCode::code("params_error", "money");
        }
        $model = new trDriver();
        $data = $model->getFields("id,balance", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]], true, false);
        if(empty($data)){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "司机不存在";
            return $this->returnData;
        }
        if($this->params['money'] > $data["balance"]){
            return ErrorCode::code("customized", "提现金额不能大于账户余额");
        }
        $withdrawData = trSystemSet::getValue("withdrawConfig");
        if(empty($withdrawData["withdrawNum"])){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "提现规则未设置";
            return $this->returnData;
        }
        $count = trCache::getValue("value", ["key" => "driverWithdraw_" . $data["id"]]);
        if($count && $count >= $withdrawData["withdrawNum"]){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "已达到最大提现次数，请明天再尝试";
            return $this->returnData;
        }else{
            $count = 0;
        }
        if($withdrawData["withdrawMaxStatus"] != "0" && floatval($withdrawData["withdrawMax"]) < $this->params["money"]){
            return ErrorCode::code("customized", "提现金额最高为{$withdrawData["withdrawMax"]}元，当前已超过");
        }
        if($withdrawData["withdrawMinStatus"] != "0" && floatval($withdrawData["withdrawMin"]) > $this->params["money"]){
            return ErrorCode::code("customized", "提现金额最低为{$withdrawData["withdrawMin"]}元，当前不满足");
        }
        $res = commonModel::toAdd(transferTable, [
            "driver_id" => $data["id"],
            "type" => 1,  // 类型；1司机提现，2其它
            "money" => $this->params["money"],
            "status" => 1,  // 状态：1未提现；2已提现；3已拒绝
            "ip" => Tools::get_client_ip(),
            "mall_id" => request()->mallData["id"],
            "create_time" => time()
        ]);
        if(isset($res["code"])){
            return $res;
        }
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "提交提现申请单失败";
        }
        trCache::saveCache([
            "key" => "driverWithdraw_" . $data["id"],
            "value" => $count+1,
            "time" => mktime(23, 59, 59, date('m'), date('d'), date('Y')) - time()
        ]); // 报错提现次数
        return $this->returnData;
    }

    public function getOrderDetail(){
        $driverModel = new trDriver();
        $driverId = $driverModel->getValue("id", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(!$driverId){
            return ErrorCode::code("customized", "该用户不是司机");
        }
        if (empty($this->params["orderSn"])) {
            return ErrorCode::code("params_not_exist", "orderSn");
        }
        $model = new trOrder();
        $data = $model->getFields("*", ["order_sn" => $this->params["orderSn"], "allot_driver_id" => $driverId]);
        if($data) {
            if(($i = strrpos($data["addressFrom"], " ")) !== false) {
                $data["addressFromDetail"] = substr($data["addressFrom"], $i + 1);
                $data["addressFrom"] = substr($data["addressFrom"], 0, $i);
            }
            if(($i = strrpos($data["addressTo"], " ")) !== false) {
                $data["addressToDetail"] = substr($data["addressTo"], $i + 1);
                $data["addressTo"] = substr($data["addressTo"], 0, $i);
            }
        }
        $this->returnData["data"] = $data;
        return $this->returnData;
    }

    // 待接收的司机订单
    public function driverNoReceivedOrder(){ // 订单状态：1待支付，2已支付，3已取消；4待分配；5已分配；6司机拒接；7司机已接单；8已完成；9已退款
        $driverModel = new trDriver();
        $driverId = $driverModel->getValue("id", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(!$driverId){
            return ErrorCode::code("customized", "该用户不是司机");
        }
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        $orderModel = new trOrder();
        $orderData = $orderModel->getList("order_sn,type,address_from,address_to,pay_money,pay_time,long_lat_from,long_lat_to", ["allot_driver_id" => $driverId, "status" => 5], $page, $pageSize);
        if(!$orderData["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $this->returnData['data'] = ['list' => $orderData['data'], 'totalPage' => $orderData['last_page'], 'currentPage' => $orderData['current_page'], 'count' => $orderData['total']];
        }
        return $this->returnData;
    }

    // 拒接收的订单
    public function driverRefuseOrder(){
        $driverModel = new trDriver();
        if(!$driverModel->getValue("id", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]])){
            return ErrorCode::code("customized", "该用户不是司机");
        }
        if(empty($this->params['orderSn'])){
            return ErrorCode::code("params_not_exist", "orderSn");
        }
        if(empty($this->params['reason'])){
            return ErrorCode::code("params_not_exist", "reason");
        }
        $orderModel = new trOrder();
        $data = $orderModel->getFields("order_sn,mobile,allot_driver_id", ["order_sn" => $this->params['orderSn'], "status" => 5]);
        if($data){
            if(!$orderModel->doUpdate(["status" => 6, "refuse" => $this->params["reason"]], ["order_sn" => $this->params['orderSn']])){
                $this->returnData = ErrorCode::code("fail");
                $this->returnData["msg"] = "更新失败";
            }else{
                SmsLogic::orderReceive($data, "fail");
            }
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "订单有误";
        }
        return $this->returnData;
    }

    // 接收订单
    public function driverAcceptOrder(){
        if(empty($this->params['orderSn'])){
            return ErrorCode::code("params_not_exist", "orderSn");
        }
        $driverModel = new trDriver();
        $driverId = $driverModel->getValue("id", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(!$driverId){
            return ErrorCode::code("customized", "该用户不是司机");
        }
        $orderModel = new trOrder();
        $data = $orderModel->getFields("order_sn,mobile,allot_driver_id", ["order_sn" => $this->params['orderSn'], "status" => 5]);
        if($data){
            if(!$orderModel->doUpdate(["status" => 7], ["order_sn" => $this->params['orderSn']])){
                $this->returnData = ErrorCode::code("fail");
                $this->returnData["msg"] = "更新失败";
            }else{
                $driverModel->doUpdate(["order_taking" => Db::raw("order_taking+1")], ["id" => $driverId]);
                SmsLogic::orderReceive($data);
            }
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "订单有误";
        }
        return $this->returnData;
    }

    // 已接收的司机订单
    public function driverReceivedOrder(){
        $driverModel = new trDriver();
        $driverId = $driverModel->getValue("id", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(!$driverId){
            return ErrorCode::code("customized", "该用户不是司机");
        }
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        $orderModel = new trOrder();
        $orderData = $orderModel->getList("order_sn,address_from,address_to,pay_time,contact_name,mobile,long_lat_from,long_lat_to", ["allot_driver_id" => $driverId, "status" => 7], $page, $pageSize);
        if(!$orderData["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $this->returnData['data'] = ['list' => $orderData['data'], 'totalPage' => $orderData['last_page'], 'currentPage' => $orderData['current_page'], 'count' => $orderData['total']];
        }
        return $this->returnData;
    }

    // 完成订单
    public function driverFinishOrder(){
        if(empty($this->params['orderSn'])){
            return ErrorCode::code("params_not_exist", "orderSn");
        }
        $driverModel = new trDriver();
        $driverId = $driverModel->getValue("id", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(!$driverId){
            return ErrorCode::code("customized", "该用户不是司机");
        }
        $orderModel = new trOrder();
        $data = $orderModel->getFields("order_sn,mobile", ["order_sn" => $this->params['orderSn'], "status" => 7]);
        if($data){
            if(!$orderModel->doUpdate(["status" => 8], ["order_sn" => $this->params['orderSn']])){
                $this->returnData = ErrorCode::code("fail");
                $this->returnData["msg"] = "更新失败";
            }else{
                SmsLogic::orderFinish($data);
            }
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "订单有误";
        }
        return $this->returnData;
    }

    // 已完成的司机订单
    public function driverCompleteOrder(){
        $driverModel = new trDriver();
        $driverId = $driverModel->getValue("id", ["openid" => request()->userLoginData["openid"], "mall_id" => request()->mallData["id"]]);
        if(!$driverId){
            return ErrorCode::code("customized", "该用户不是司机");
        }
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        $orderModel = new trOrder();
        $orderData = $orderModel->getList("order_sn,address_from,address_to,pay_time,contact_name,mobile,status,long_lat_from,long_lat_to", [["allot_driver_id", "=", $driverId], ["status", "in", "8,6"]], $page, $pageSize);
        if(!$orderData["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $this->returnData['data'] = ['list' => $orderData['data'], 'totalPage' => $orderData['last_page'], 'currentPage' => $orderData['current_page'], 'count' => $orderData['total']];
        }
        return $this->returnData;
    }
}